package com.liusand.gateway.filter;

import cn.hutool.json.JSONException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.liusand.common.constans.SecretKey;
import com.liusand.gateway.config.WhiteFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;



import java.util.List;
import java.util.function.Consumer;

/**
 * @author :liusha
 * packageName :com.liusand.gateway.filter
 * fileName :GloablFilter
 * creationTime :2022/12/13 15:58
 */
@Order(0)
@Component
public class AuthorizeFilter implements GlobalFilter {

    @Autowired
    private WhiteFilter whiteFilter;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders requestHeaders = exchange.getRequest().getHeaders();

        List<String> whiteList = whiteFilter.getWhite();
        String url = exchange.getRequest().getPath().toString();
        for(String w : whiteList){
            if(w.equals(url)){
                return chain.filter(exchange);
            }
        }

        String token = requestHeaders.getFirst("Authorization");
        if(token == null){
            return getVoidMono(exchange);
        }
        JWT jwt;
        try {
            jwt = JWTUtil.parseToken(token);
        }catch (JSONException e){
            return getVoidMono(exchange);
        }
        jwt.setKey(SecretKey.JWT_KEY.getBytes());
        boolean timeVerifyResult = jwt.validate(0);
        if(!timeVerifyResult){
            return getVoidMono(exchange);
        }
        String id = (String) jwt.getPayload("id");
        String phone = (String) jwt.getPayload("phone");
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(phone)){
            return getVoidMono(exchange);
        }
        ServerHttpRequest newRequest = exchange.getRequest().mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                httpHeaders.add("id", id);
                httpHeaders.add("phone", phone);
            }
        }).build();
        exchange.mutate().request(newRequest).build();

        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
